package com.honry.common.domain.model;

import javax.persistence.Column;
import javax.persistence.MappedSuperclass;
import javax.persistence.Version;


/**
 * 并发安全的实体层超类型
 * @author machao
 *
 */
@MappedSuperclass
public class ConcurrencySafeEntity extends Entity {
	private static final long serialVersionUID = 1L;
	@Version
	@Column(name = "concurrency_version")
	private int concurrencyVersion;
	protected ConcurrencySafeEntity() {
		super();
	}
	
	/**
	 * 并发版本号
	 * @return
	 */
	public int concurrencyVersion(){
		return this.concurrencyVersion;
	}
	public void setConcurrencyVersion(int version)
	{
		this.failWhenConcurrencyViolation(version);
		this.concurrencyVersion=version;
	}
	/**
	 * 违反并发规则时失败
	 * @param version
	 */
	public void failWhenConcurrencyViolation(int version) {
        if (version != this.concurrencyVersion()) {
            throw new IllegalStateException(
                    "并发违规: 检测到过时的数据.实体已经被修改.");
        }
    }
}
